<?php

namespace backend\widgets\Translit;

use yii\helpers\Html;
use yii\widgets\InputWidget;

class TranslitWidget extends InputWidget
{

    public $widgetOptions = [
        'class' => 'form-control',
        'translitButtonId' => 'translit-button',
        'updateButtonId' => 'update-translit-button',
    ];

    public $clientOptions = [];


    public function init()
    {
        if(!$this->clientOptions['isNewRecord'])
        {
            $this->widgetOptions['disabled'] = 'disabled';
        }
        parent::init();
    }

    public function run()
    {   
        if ($this->model === null) 
        {
            echo Html::textInput($this->name, $this->value, $this->widgetOptions);
        } 
        else 
        {
            echo '<div class="input-group">';

            echo Html::activeTextInput($this->model, $this->attribute, $this->widgetOptions);

            if($this->clientOptions['isNewRecord']) echo '<div class="input-group-addon"><span class="glyphicon glyphicon-download-alt"></span></div>';
            else echo '<div class="input-group-addon"><span class="glyphicon glyphicon-lock"></span></div>';
            
            echo '</div>';

            echo Html::a('Получить', '#', $options = [
                'id' => $this->widgetOptions['translitButtonId'], 
                'class' => 'btn btn-success' . ($this->clientOptions['isNewRecord'] == false ? ' disabled' : ''), 
                'style' => 'margin-top: 5px;',
                'role' => 'button',
            ]);
            
            if(\Yii::$app->user->can('updateAlias') && !$this->clientOptions['isNewRecord'])
            {
                echo Html::a('Редактировать', '#', $options = [
                    'id' => $this->widgetOptions['updateButtonId'], 
                    'class' => 'btn btn-success',
                    'style' => 'margin: 5px 0 0 10px;',
                    'role' => 'button', 
                ]);
            }
        }
        
        $this->registerPlugin();
    }

    protected function registerPlugin()
    {
        
        $destinationId = $this->clientOptions['source'];
        $translitButtonId =  $this->widgetOptions['translitButtonId'];
        $updateButtonId = $this->widgetOptions['updateButtonId'];
        $thisId = $this->options['id'];

        $view = $this->getView();

        TranslitAsset::register($view);

        $view->registerJs("$('#$thisId').translit({ 
                destination: '$destinationId',
                button: '$translitButtonId',
                updateButton: '$updateButtonId',
            });");

    }
}
